package com.chenyuhan.myview.testview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import com.chenyuhan.myview.R;

/**
 * Created by Administrator on 2017/6/27 0027.
 */

public class TestImageView extends View {
    private final String TAG = TestImageView.class.getSimpleName();
    /**
     * 文本
     */
    private String mText;
    /**
     * 文本颜色
     */
    private int mTextColor;
    /**
     * 文本大小
     */
    private int mTextSize;

    /**
     * 图片
     */
    private Bitmap mImage;

    /**
     * 图像比例尺类型
     */
    private int mImgScaleType;
    private final int FILLXY = 0;
    private final int CENTER = 1;

    /**
     * 绘制时控制文本绘制的范围
     */
    private Paint mPaint;
    private Rect mBound;
    private Rect rect;


    public TestImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TestImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        /**
         * 获得我们所定义的自定义样式属性
         */
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TestImageView, defStyleAttr, 0);
        for (int i = 0; i < typedArray.getIndexCount(); i++) {
            int attr = typedArray.getIndex(i);
            switch (attr) {
                case R.styleable.TestImageView_textOne:
                    mText = typedArray.getString(attr);
                    break;
                case R.styleable.TestImageView_textColorOne:
                    // 默认颜色设置为黑色
                    mTextColor = typedArray.getColor(attr, Color.BLACK);
                    break;
                case R.styleable.TestImageView_textSizeOne:
                    // 默认设置为16sp，TypeValue也可以把sp转化为px
                    mTextSize = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
                    break;
                case R.styleable.TestImageView_image:
                    mImage = BitmapFactory.decodeResource(getResources(), typedArray.getResourceId(attr, 0));
                    break;
                case R.styleable.TestImageView_imageScaleType:
                    mImgScaleType = typedArray.getInt(attr, 0);
                    break;
            }
        }
        typedArray.recycle();
        mPaint = new Paint();
        mBound = new Rect();
        if (mTextSize != 0)
            mPaint.setTextSize(mTextSize);
        if (mText != null)
            // 计算了描绘字体需要的范围
            mPaint.getTextBounds(mText, 0, mText.length(), mBound);
    }

    private int mWidth;
    private int mHeight;
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        /**
         * 设置宽度
         */
        mWidth = 0;
        switch (widthMode) {
            case MeasureSpec.EXACTLY:
                mWidth = widthSize;
                break;
            case MeasureSpec.AT_MOST:
                // 由图片决定的宽
                int desireByImg = getPaddingLeft() + getPaddingRight() + mImage.getWidth();
                // 由字体决定的宽
                int desireByTitle = getPaddingLeft() + getPaddingRight() + mBound.right;
                int desire = Math.max(desireByImg, desireByTitle);
                mWidth = Math.min(desire, widthSize);
                break;
        }
        /**
         * 设置高度
         */
        mHeight = 0;
        switch (heightMode) {
            case MeasureSpec.EXACTLY:
                mHeight = heightSize;
                break;
            case MeasureSpec.AT_MOST:
                int desire = getPaddingTop() + getPaddingBottom() + mImage.getHeight() + mBound.height();
                mHeight = Math.min(desire, heightSize);
                break;
        }
        setMeasuredDimension(mWidth, mHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        /**
         * 边框
         */
        mPaint.setStrokeWidth(4);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.CYAN);
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);

        rect = new Rect();
        rect.left = getPaddingLeft();
        rect.right = mWidth - getPaddingRight();
        rect.top = getPaddingTop();
        rect.bottom = mHeight - getPaddingBottom();

        mPaint.setColor(mTextColor);
        mPaint.setStyle(Paint.Style.FILL);
        //判断是否有设置文字
        if (mText != null) {
            /**
             * 当前设置的宽度小于字体需要的宽度，将字体改为xxx...
             */
            if (mBound.width() > mWidth) {
                TextPaint paint = new TextPaint(mPaint);
                String msg = TextUtils.ellipsize(mText, paint, (float) mWidth - getPaddingLeft() - getPaddingRight(),
                        TextUtils.TruncateAt.END).toString();
                canvas.drawText(msg, getPaddingLeft(), mHeight - getPaddingBottom(), mPaint);
            } else {
                //正常情况，将字体居中
                canvas.drawText(mText, mWidth / 2 - mBound.right * 1.0f / 2, mHeight - getPaddingBottom(), mPaint);
            }
            //将底边减掉文字的高度，降低底边的位置
            rect.bottom -= mBound.height();
        }

        //设置图片的矩形大小
        Rect imgRect = new Rect();
        imgRect.left = 0;
        imgRect.right = mImage.getWidth();
        imgRect.top = 0;
        imgRect.bottom = mImage.getHeight();
        if (mImgScaleType == FILLXY) {
            canvas.drawBitmap(mImage, null, imgRect, mPaint);
        } else if (mImgScaleType == CENTER) {
            //计算居中的矩形范围
            imgRect.left = mWidth / 2 - imgRect.right / 2;
            imgRect.right = mWidth / 2 + imgRect.right / 2;
            imgRect.top = (mHeight - mBound.height()) / 2 - imgRect.bottom / 2;
            imgRect.bottom = (mHeight - mBound.height()) / 2 + imgRect.bottom / 2;

            canvas.drawBitmap(mImage, null, imgRect, mPaint);
        }
    }
}
